﻿using Newtonsoft.Json.Linq;
using System;
using up6.db.model;
using up6.db.sql;
using up6.db.utils;
using up6.utils;

namespace up6.filemgr.app
{
    /// <summary>
    /// 构建文件夹下载数据
    /// 格式：
    /// [
    ///   {nameLoc,pathSvr,pathRel,lenSvr,sizeSvr}
    ///   {nameLoc,pathSvr,pathRel,lenSvr,sizeSvr}
    /// ]
    /// </summary>
    public class FolderBuilder
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">文件夹ID</param>
        /// <returns></returns>
        public JToken build(string id,string pid) {
            var o = SqlTable.build("up6_files").readOne<DnFileInf>(SqlWhere.build().eq("f_id", id));
            //子目录
            if (o == null)
                o = SqlTable.build("up6_folders").readOne<DnFileInf>(SqlWhere.build().eq("f_id", id));

            string pathRoot = o.pathRel;
            var index = pathRoot.Length;

            //查询文件：select * from up6_files where CHARINDEX('/folder/',f_pathRel)=1
            string where = string.Format("CHARINDEX('{0}',f_pathRel)=1", pathRoot+"/");
            if(ConfigReader.dbType() == DataBaseType.Oracle) 
                where = string.Format("instr(f_pathRel,'{0}')=1", pathRoot + "/");

            var files = SqlTable.build("up6_files").reads<DnFileInf>(
                SqlWhere.build()
                .sql("f_pathRel", where)
                .eq("f_fdTask",false)
                .eq("f_deleted",false)
                );
            foreach (DnFileInf f in files)
            {
                f.f_id = f.id;
                //删除父级路径，控件会自动拼接
                f.pathRel = f.pathRel.Substring(index);
                f.lenSvrSec = f.lenLocSec;
                //提供给对象存储
                f.fields.Add("object_key", PathTool.url_safe_encode(f.object_key));
            }
            return JToken.FromObject(files);
        }
    }
}